#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#include<conio.h>
#include<time.h>



//全局变量
int high=18,width;  //游戏画面尺寸
int ball_x,ball_y;   //小球坐标 
int ball_vx,ball_vy;  //小球速度 
int position_x,position_y;// 挡板中心坐标
int radius; 				 //挡板半径
int left,right;  			// 挡板左右边界
int ball_number;             //反弹次数 
int brick_x,brick_y;          //砖块位置 
int score;                   //游戏得分 

int gotoxy(int x,int y)//光标移动到（x，y） 位置 
{
	HANDLE handle = GetStdHandle (STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition (handle, pos);
} 

void HideCursor()
{
	CONSOLE_CURSOR_INFO cursor_info={1,0}; //第二个值为0表示隐藏光标
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
} 

int starup()//游戏初始化 
{
	high=18;
	width=30;
	
	ball_x=1;
	ball_y=width/3;
	
	ball_vx=1;
	ball_vy=1;
	
	position_x=high;
	position_y=width/2;
	radius=5;
	left= position_y-radius;
	right=position_y+radius;
	
	ball_number=0;
	
	brick_x=rand()%(high/3);
	brick_y=rand()%width;
	
	score=0;
	
	HideCursor(); //隐藏光标
}

int show()//游戏显示
{	

	
	gotoxy(0,0);//清屏 
	int i,j;
	for(i=0;i<=high+1;i++)
	{
		for(j=0;j<=width;j++)
		{
			if(i==ball_x&&j==ball_y)
				printf("*");    //输出小球 
			else if(j==width)
				printf("|");  //输出右边界 
			else if(i==high+1)
				printf("_");  //输出下边界
			else if((i==high)&&(j>=left)&&(j<=right))
				printf("*");   //输出挡板
			else if(i==brick_x&&j==brick_y)
				printf("@");	//输出砖块	
			else 
				printf(" ");
		}
		printf("\n");
	}
	printf("反弹次数:%d\n",ball_number);
	printf("分数:%d",score); 
}

int updataWithoutInput()//用户无关设置
{	
	if(ball_x==high-1)
	{
		if(ball_y>=left&&ball_y<=right)
		{
			ball_number++;
			ball_vx=-ball_vx;
		}
	}
	if(ball_x==high)
	{
		printf("Game Over!");
		exit(0);
	}
		
	
	if(ball_x==brick_x&&ball_y==brick_y)
	{
		score++;
		brick_x=rand()%(high/3);
		brick_y=rand()%width;
		ball_vx=-ball_vx;
		ball_vy=-ball_vy;
		printf("\a");	
	}
	//根据速度更新小球位置 
	ball_x=ball_x+ball_vx;
	ball_y=ball_y+ball_vy;
	
	//碰边界后改变速度方向,实现反弹 
	if (ball_x==0)
	{
		ball_vx=-ball_vx;
	}
	if (ball_y==0||ball_y==width-1)
		ball_vy=-ball_vy;
	
	
	Sleep(150);
}

int updataWithInput()//用户有关设置
{
	char input;
	
	if(kbhit())//当按下键时执行
	{
		input=getch(); 
		if(input=='a')
		{
			if(left>0)
			{
				position_y--;
				left=position_y-radius;
				right=position_y+radius;
			}
			
		}
		if(input=='d')
		{
			if(right<width-1)
			{
				position_y++;
				left=position_y-radius;
				right=position_y+radius;
			}
		
		}		 
	
	} 
}

int main()
{
	srand((int)time(0));
	starup();//数据初始化
	while(1)//游戏循环 
	{
		show();//游戏显示 
		updataWithoutInput();//用户无关设置 
		updataWithInput(); //用户有关设置 
	} 
	return 0; 
} 
